package com.yunnuo.system.mould.controller;

import com.yunnuo.system.comm.util.AsyncFactory;
import com.yunnuo.system.comm.util.AsyncManager;
import com.yunnuo.system.comm.util.ResultData;
import com.yunnuo.system.dept.entity.Dept;
import com.yunnuo.system.dept.service.IDeptService;
import com.yunnuo.system.users.entity.User;
import net.sf.json.JSON;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 下载/导入模板
 * @author 魏洪福（15064000912@163.com）
 * @create 2018-09-10-14:00
 */
@Controller
@RequestMapping("/system/mould")
public class MouldController {

    private String prefix = "system/mould";

    @Autowired
    private IDeptService deptService;

    @GetMapping("/mouldUser")
    public String mouldUser()
    {
        return prefix + "/mouldUser";
    }

    @GetMapping("/mouldDept")
    public String mouldDept()
    {
        return prefix + "/mouldDept";
    }

    /**
     * 下载模板
     * @return
     */
    @RequestMapping("/downLoad/{flag}")
    public void downLoad(@PathVariable("flag")String flag, HttpServletRequest request, HttpServletResponse response)
    {
        String fileName ="";
        if("1".equals(flag)){
            fileName ="mouldUser.xlsx";
        }else {
            fileName ="mouldDept.xlsx";
        }
        try {
            InputStream fis = MouldController.class.getResourceAsStream("/static/yunnuo/excle/mouldExcle/"+fileName);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            response.setContentType("bin");
            String fileNames = fileName;
            String agent = request.getHeader("USER-AGENT");
            String codedfilename = "";
            // ie
            if (null != agent && -1 != agent.indexOf("MSIE") || null != agent && -1 != agent.indexOf("Trident")) {
                String name = java.net.URLEncoder.encode(fileNames, "UTF8");
                codedfilename = name;
                // 火狐,chrome等
            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
                codedfilename = new String(fileNames.getBytes("UTF-8"), "iso-8859-1");
            }
            response.addHeader("Content-Disposition", "attachment; filename=\"" + codedfilename + "\"");
            response.getOutputStream().write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 上传信息
     * @return
     */
    @RequestMapping("/upLoad/{flag}")
    @ResponseBody
    public JSON  upLoad(@PathVariable("flag")String flag, @RequestParam("file") MultipartFile multipartFile)
    {
        //1.判断文件是否为空
        if(multipartFile.isEmpty()){
            throw new RuntimeException("MouldController.downLoad():上传的文件为空！");
        }
        ResultData data = new ResultData();
        InputStream is=null;
        try{
               is = multipartFile.getInputStream();
              //4.处理文件
            XSSFWorkbook excle=new XSSFWorkbook(is);
            User user=null;
            Dept dept=null;

            //循环工作表
            XSSFSheet sheet=excle.getSheetAt(0);
            if(null==sheet){
                throw new RuntimeException("MouldController.downLoad():没有用户信息！");
            }
            //第一行是表头，从第二行开始
            for (int rowNum=1;rowNum<sheet.getLastRowNum();rowNum++){
                XSSFRow row=sheet.getRow(rowNum);
                if(null==row) continue;

                StringBuffer sb=new StringBuffer();
                for (int cellNum=0;cellNum<=row.getLastCellNum();cellNum++){
                    XSSFCell cell=row.getCell(cellNum);
                    if(null==cell){
                        sb.append(" ;");
                    }else if(cell.getCellType()==0){
                        sb.append(cell.getNumericCellValue() + ";");
                    }else{
                        sb.append(cell.getStringCellValue() + ";");
                    }
                }
                String[] sbs=sb.toString().split(";");

                System.out.println("20180913");
                for (String sb1:sbs
                     ) {
                    System.out.println(sb1);
                }
                if ("1".equals(flag)){
                    user=new User();
                    user.setLoginName(sbs[0]);
                    user.setRealName(sbs[1]);
                    user.setPassword(sbs[2]);
                    user.setDeptName(sbs[3]);
                    user.setUserStatus(sbs[4]);
                    user.setEmail(sbs[5]);
                    user.setPhone(sbs[6]);
                    user.setSex(sbs[7]);
                    //使用异步保存用户
                    AsyncManager.me().execute(AsyncFactory.recordUser(user,sbs[8]));
                }else {
                    dept=new Dept();
                    dept.setDeptName(sbs[0]);
                    dept.setOrderNum(sbs[1]);
                    dept.setDeptStatus( (int)Double.parseDouble(sbs[2]));
                    dept.setParentName(sbs[3]);
                    //不能使用异步保存部门  原因：异步保存上级部门可能创建时间晚
//                    AsyncManager.me().execute(AsyncFactory.recordDept(dept));
                    deptService.save(dept);
                }
            }
            data.setStat(ResultData.STAT_SUCCESS);
            data.setMessage("上传成功！");
        }catch (Exception e){
            e.printStackTrace();
            data.setStat(ResultData.STAT_FAILURE);
            data.setMessage("上传失败！");
        }
        return data.toJson();
    }

    public static void main(String[] args)  {
        System.out.println(MouldController.class.getResourceAsStream("/banner.txt"));
        InputStream fis = MouldController.class.getResourceAsStream("/static/yunnuo/excle//mouldExcle//mouldUser.xlsx");
        System.out.print(fis);
    }
}
